<script lang="ts" setup>
  import { ref, onMounted, onUnmounted, watch, nextTick, computed, withDefaults } from 'vue';
  import * as echarts from 'echarts/core';
  interface ChartProps {
    dataBarSet: number[];
    dataBarReal: number[];
    dataLine: number[];
    datax: string[];
    yAxisName: [string, string];
    dataName: [string, string, string];
    title: string;
    targetRollCounts: number[] | Record<string, number>;
    actualRollCounts: number[] | Record<string, number>;
  }

  const props = withDefaults(defineProps<ChartProps>(), {
    yAxisName: () => ['产量', '达成率'],
    dataName: () => ['预测产量', '实际产量', '达成率'],
    title: '酸轧机组产量',
    targetRollCounts: () => [],
    actualRollCounts: () => [],
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  // 单一引用的工具函数与回调，放到外层避免重复创建
  const dot = (color: string) =>
    `<span style="display:inline-block;width:10px;height:10px;background-color:${color};border-radius:50%;margin-right:5px;"></span>`;

  const getCountBy = (coll: number[] | Record<string, number> | undefined, dataIndex: number, categoryName: string): number | undefined => {
    if (!coll) return undefined;
    if (Array.isArray(coll)) return coll[dataIndex];
    if (typeof coll === 'object') return coll[categoryName];
    return undefined;
  };

  const resolveSeriesData = (coll: number[] | Record<string, number> | undefined): number[] => {
    if (!coll) return [];
    if (Array.isArray(coll)) return coll;
    const categories = props.datax ?? [];
    return categories.map((name, index) => getCountBy(coll, index, name) ?? 0);
  };

  const tooltipPosition = (point: any) => [point[0], point[1] + 20];

  const formatTooltip = (params: any) => {
    if (!Array.isArray(params) || params.length === 0) return '';
    const dataIndex = params[0]?.dataIndex ?? 0;
    const categoryName = params[0]?.name ?? '';

    const byName: Record<string, any> = {};
    for (const it of params) byName[it.seriesName] = it;

    const header = categoryName || '';
    const rows: { label: string; value: string }[] = [];

    const formatPercent = (val: number) => {
      const p = val <= 1 ? val * 100 : val;
      const n = Number(p);
      if (!Number.isFinite(n)) return '-%';
      const s = n.toFixed(2).replace(/\.00$/, '');
      return `${s}%`;
    };

    const targetColor = byName['预测产量']?.color || '#ff9c39';
    const actualColor = byName['实际产量']?.color || '#029cc7';
    const rateColor = byName['达成率']?.color || '#91cc75';

    const targetCount = getCountBy(props.targetRollCounts, dataIndex, categoryName);
    const actualCount = getCountBy(props.actualRollCounts, dataIndex, categoryName);
    const targetProd = Array.isArray(props.dataBarSet) ? props.dataBarSet[dataIndex] : undefined;
    const actualProd = Array.isArray(props.dataBarReal) ? props.dataBarReal[dataIndex] : undefined;

    if (targetCount !== undefined) rows.push({ label: `${dot(targetColor)}预测生产卷数`, value: `${targetCount}` });
    if (targetProd !== undefined) rows.push({ label: `${dot(targetColor)}预测产量`, value: `${targetProd}` });
    if (actualCount !== undefined) rows.push({ label: `${dot(actualColor)}实际生产卷数`, value: `${actualCount}` });
    if (actualProd !== undefined) rows.push({ label: `${dot(actualColor)}实际产量`, value: `${actualProd}` });

    if (byName['达成率']) {
      rows.push({ label: `${dot(rateColor)}达成率`, value: formatPercent(Number(byName['达成率'].value)) });
    }

    const table = `<table style="border-collapse:collapse;">
      ${rows
        .map(
          (r) =>
            `<tr>
              <td style=\"padding:0 10px 0 0;white-space:nowrap;\">${r.label}</td>
              <td style=\"text-align:right;white-space:nowrap;\">${r.value}</td>
            </tr>`
        )
        .join('')}
    </table>`;
    return `${header ? `${header}<br/>` : ''}${table}`;
  };

  // 使用计算属性来生成图表配置
  const chartOption = computed(() => {
    return {
      title: {
        text: props.title,
        left: 'center',
        textStyle: {
          fontSize: 14,
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' },
        appendToBody: true,
        position: tooltipPosition,
        formatter: formatTooltip,
      },
      legend: {
        data: props.dataName,
        top: props.title === '' ? '0%' : '10%',
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: props.datax ?? [],
      },
      yAxis: [
        {
          type: 'value',
          name: props.yAxisName[0],
          axisLabel: {
            formatter: '{value}',
          },
        },
        {
          type: 'value',
          name: props.yAxisName[1],
          axisLabel: {
            formatter: '{value}%',
          },
          position: 'right',
        },
      ],
      series: [
        {
          name: props.dataName[0],
          type: 'bar',
          data: resolveSeriesData(props.targetRollCounts),
          yAxisIndex: 0,
          itemStyle: {
            color: '#ff9c39',
            borderRadius: [8, 8, 8, 8],
            opacity: 0.9,
          },
        },
        {
          name: props.dataName[1],
          type: 'bar',
          data: resolveSeriesData(props.actualRollCounts),
          yAxisIndex: 0,
          itemStyle: {
            color: '#029cc7',
            borderRadius: [8, 8, 8, 8],
            opacity: 0.9,
          },
        },
        {
          name: props.dataName[2],
          type: 'line',
          data: props.dataLine ?? [],
          yAxisIndex: 1,
          symbol: 'circle',
          symbolSize: 4,
          itemStyle: {
            color: '#91cc75',
          },
        },
      ],
    };
  });

  const initCharts = () => {
    try {
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(chartOption.value, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    if (chartInstance) {
      chartInstance.setOption(chartOption.value, true);
    }
  };

  // 窗口大小变化处理
  const handleResize = () => {
    nextTick(() => {
      chartInstance?.resize();
    });
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      initCharts();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', handleResize);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', handleResize);
    chartInstance?.dispose();
  });

  // 监听计算属性变化，自动更新图表
  watch(
    chartOption,
    () => {
      if (chartInstance) {
        updateChart();
      }
    },
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
  });
</script>
<template>
  <div ref="chartRef" class="chart-container">
    <!-- <m-echarts :option="option"></m-echarts> -->
  </div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
